package cn.lzx.hrm.controller;

import cn.lzx.exctption.GlobalException;
import cn.lzx.hrm.util.SmsUtil;
import cn.lzx.util.AjaxResult;
import cn.lzx.util.StrUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/smsVerifyCode")
public class SmsVerifyCodeController {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送验证码
     * @param params
     * @return
     */
    @PostMapping("/sendVerifyCode")
    public AjaxResult sendSmsVerifyCode(@RequestBody Map<String,String> params){
        String key = params.get("key");
        String codeNum = params.get("codeNum");
        String expire = params.get("expire");
        String phone = params.get("phone");
        String obj = (String) redisTemplate.opsForValue().get(key);
        String code = null;
        if(!StringUtils.isEmpty(obj)){ //验证码没有过期
            //获取redis中以前保存的验证码
            code = obj.split(":")[0];
            //获取以前保存的时间
            String timeString = obj.toString().split(":")[1];
            if(System.currentTimeMillis() - Long.parseLong(timeString) < 1*60*1000){ //没有过重发时间
                throw new GlobalException("不能重复发送验证码");
            }
        }else{ //过期了 或 第一次发送
            //重新生成验证码
            code = StrUtils.getRandomString(Integer.valueOf(codeNum));
        }
        //设置值到redis
        redisTemplate.opsForValue().set(key,code+":"+System.currentTimeMillis(),3, TimeUnit.MINUTES);

        //发送短信验证码
        //SmsUtil.sendMsg(phone,"你的验证码是：" + code + ",请在3分钟之内使用");
        System.out.println("你的验证码是：" + code + ",请在3分钟之内使用");
        return AjaxResult.me();
    }


    /**
     * 校验手机验证码
     */
    @PostMapping("/verify")
    public  AjaxResult verifySmsCode(@RequestBody Map<String,String> params){
        String key = params.get("key");
        String code = params.get("code");
        String ridesCode = (String)redisTemplate.opsForValue().get(key);
        if (StringUtils.isEmpty(ridesCode)){
            return AjaxResult.me().setSuccess(false).setMessage("验证码错误！");
        }
        return code.equalsIgnoreCase(ridesCode.split(":")[0])?AjaxResult.me()
                :AjaxResult.me().setSuccess(false).setMessage("短信验证码不正确！") ;
    }
}
